package com.example.fun.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.fun.R;
import com.example.fun.bean.PopSiteBean;

import java.util.ArrayList;
import java.util.List;

public class PopSiteAdapter extends RecyclerView.Adapter<PopSiteAdapter.PopSiteViewHolder> {
    private List<PopSiteBean.DataDTO> list = new ArrayList<>();
    private LayoutInflater inflater;
    private Context context;
    private OnItemClickListener onItemClickListener;

    public void setList(List<PopSiteBean.DataDTO> list){
        if(list != null){
            this.list.addAll(list);
        }
        notifyDataSetChanged();
    }

    public PopSiteAdapter(List<PopSiteBean.DataDTO> list, Context context){
        if (list != null) {
            this.list.addAll(list);
        }
        inflater = LayoutInflater.from(context);
        this.context = context;
    }

    @NonNull
    @Override
    public PopSiteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_popsite, parent, false);
        PopSiteViewHolder popSiteViewHolder = new PopSiteViewHolder(view);
        return popSiteViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull PopSiteViewHolder holder, int position) {
        PopSiteBean.DataDTO popSiteBean = list.get(position);
        String category = new String(popSiteBean.getName() + "：" + popSiteBean.getCategory());
        holder.tvCategory.setText(category);

        int adapterPosition = holder.getAdapterPosition();
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onItemClickListener != null){
                    onItemClickListener.onItemClick(holder.itemView, adapterPosition);
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public List<PopSiteBean.DataDTO> getList(){
        return list;
    }

    static class PopSiteViewHolder extends RecyclerView.ViewHolder {
        private View itemView;
        TextView tvCategory;

        public PopSiteViewHolder(@NonNull View itemView) {
            super(itemView);
            this.itemView = itemView;
            tvCategory = itemView.findViewById(R.id.tv_category);
        }
    }

    public interface OnItemClickListener{
        void onItemClick(View view, int position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }
}
